$(function () {
    var today;//今天日期
    // 信息常量
    var num;//航班号
    var datetimepicker;//日期
    var departureCity;// 出发城市
    var arrivalCity;//到达城市
    var airlineCompany;//航班公司
    var departureTime;//出发时间
    var arrivalTime;//到达时间
    var businessNum;//公务舱人数
    var businessPrice;//公务舱价格
    var economyNum;//经济舱人数
    var economyPrice;//经济舱价格
    // 获取当日日期填充到日期选择框
    function get_date() {
        //创建一个当前日期对象
        var now = new Date();
        //格式化日，如果小于9，前面补0
        var day = ("0" + now.getDate()).slice(-2);
        //格式化月，如果小于9，前面补0
        var month = ("0" + (now.getMonth() + 1)).slice(-2);
        //拼装完整日期格式
        today = now.getFullYear() + "-" + (month) + "-" + (day);
        //完成赋值
        $("#datetimepicker1").val(today);
        $("#departureTime").val(today + "T00:00");
        $("#arrivalTime").val(today + "T00:00");
    }
    function login() {
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/admin',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("adminToken")
            },
            success: function (res) {

                if (!res.success) return alert('未登录！');
                else {
                    $('#login').text(res.data.admin['name'] + "/退出登录");
                    ID = res.data.admin['identityNumber'];
                }
            }
        })

    }
    console.log(localStorage.getItem('ID'));
    // 获取航班信息
    function get_information(){
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/flights/admin',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("adminToken")
            },
            success: function (res) { var string="";
            for(var i=0;i<res.data.list.length;i++)
            {
                string=string+ '<tr><td><div class="row"><h2 class="col">'+
                res.data.list[i]['departure']+'</h2><h4 class="col">'+
                res.data.list[i]['flightNum']+'</h4><h2 class="col">'+
                res.data.list[i]['destination']+'</h2></div></td><td>'+
                res.data.list[i]['departureTime']+'</td><td>'+
                res.data.list[i]['arrivalTime']+'</td><td>' +
                res.data.list[i]['businessClassPrice']+'</td><td> '+
                res.data.list[i]['businessClassAvailable']+'</td><td>'+
                res.data.list[i]['economyClassPrice']+'</td><td>'+
                res.data.list[i]['economyClassAvailable']+'</td><td><input type="button" class="btn btn-success alterButton" value="修改" flightid="'+
                res.data.list[i]['fid']+'" data-bs-toggle="modal" data-bs-target="#changeModal"> <input type="button" class="btn btn-danger delButton" value="删除" flightid="'+
                res.data.list[i]['fid']+ '" data-bs-toggle="modal" data-bs-target="#deleteModal"></td></tr>';
            }
            var $tr = $(string);
            //把创建出来的$tr追加到tbody中去.
           $('#informationTable').empty().append($tr);
        }
        })
        // $.get('http://localhost/flights/admin?', function (res) {
        //     var string="";
        //     for(var i=0;i<res.data.list.length;i++)
        //     {
        //         string=string+ '<tr><td><div class="row"><h2 class="col">'+
        //         res.data.list[i]['departure']+'</h2><h4 class="col">'+
        //         res.data.list[i]['flightNum']+'</h4><h2 class="col">'+
        //         res.data.list[i]['destination']+'</h2></div></td><td>'+
        //         res.data.list[i]['departureTime']+'</td><td>'+
        //         res.data.list[i]['arrivalTime']+'</td><td>' +
        //         res.data.list[i]['businessClassPrice']+'</td><td> '+
        //         res.data.list[i]['businessClassAvailable']+'</td><td>'+
        //         res.data.list[i]['economyClassPrice']+'</td><td>'+
        //         res.data.list[i]['economyClassAvailable']+'</td><td><input type="button" class="btn btn-success alterButton" value="修改" flightid="'+
        //         res.data.list[i]['fid']+'" data-bs-toggle="modal" data-bs-target="#changeModal"> <input type="button" class="btn btn-danger delButton" value="删除" flightid="'+
        //         res.data.list[i]['fid']+ '" data-bs-toggle="modal" data-bs-target="#deleteModal"></td></tr>';
        //     }
        //     var $tr = $(string);
        //     //把创建出来的$tr追加到tbody中去.
        //    $('#informationTable').empty().append($tr);
        // })
    }
    login();
    get_date();
    // 获取航班信息
    get_information();
    //导航栏航班信息按钮
    $("#nav1").on("click", function () {
        $('#fligthAddition').hide();//航班添加隐藏
        $('#allFlightOrders').hide();//航班预定情况隐藏
        $('#flightInformation').show();//航班信息显示
    });
    //导航栏新增航班按钮
    $("#nav2").on("click", function () {
        $('#allFlightOrders').hide();//航班预定情况隐藏
        $('#flightInformation').hide();//航班信息隐藏
        $('#fligthAddition').show();//航班添加显示
    });
    //导航栏航班预定情况按钮
    $("#nav3").on("click", function () {
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/orders/admin',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("adminToken")
            },
            success: function (res) {

                if (res.code != 200) return alert('未登录！');
                else {
                   var string="";
                   for (var i = 0; i < res.data.list.length; i++) {
                    string+='<tr><td>'+
                    res.data.list[i]['flightNum']+'</td><td>'+
                    res.data.list[i]['departureTime']+'</td><td>'+
                    res.data.list[i]['classType']+'</td><td>'+
                    res.data.list[i]['name']+'</td><td>'+
                    res.data.list[i]['price']+'</td></tr>';
                   }
                   var $tr = $(string);
                   //把创建出来的$tr追加到tbody中去.
                   $('#reserveInformation').empty().append($tr);
                }
            }
        })
        $('#fligthAddition').hide();//航班添加隐藏
        $('#flightInformation').hide();//航班信息隐藏
        $('#allFlightOrders').show();//航班预定情况
    });
    // 航班信息查询按钮
    $("#queryButton1").on("click", function () {
        num = $('#flightNumber').val().trim();
        departureCity= $('#departureCity').val().trim();
        arrivalCity= $('#arrivalCity').val().trim();
        $.get('http://localhost/flights/admin?flightNum='+num+'&departure='+departureCity+'&destination='+arrivalCity, function (res) {
            if (!res.success) return alert('获取预订信息失败');
            var string="";
            if(res.data.list.length==0)
            {
                alert('无符合条件的航班');
                return;
            }
            for(var i=0;i<res.data.list.length;i++)
            {
                string=string+ '<tr><td><div class="row"><h2 class="col">'+
                res.data.list[i]['departure']+'</h2><h4 class="col">'+
                res.data.list[i]['flightNum']+'</h4><h2 class="col">'+
                res.data.list[i]['destination']+'</h2></div></td><td>'+
                res.data.list[i]['departureTime']+'</td><td>'+
                res.data.list[i]['arrivalTime']+'</td><td>' +
                res.data.list[i]['businessClassPrice']+'</td><td>'+
                res.data.list[i]['businessClassAvailable']+'</td><td>'+
                res.data.list[i]['economyClassPrice']+'</td><td>'+
                res.data.list[i]['economyClassAvailable']+'</td><td><input type="button" class="btn btn-success alterButton" value="修改" flightid="'+
                res.data.list[i]['fid']+'" data-bs-toggle="modal" data-bs-target="#changeModal"> <input type="button" class="btn btn-danger delButton" value="删除" flightid="'+
                res.data.list[i]['fid']+ '" data-bs-toggle="modal" data-bs-target="#deleteModal"></td></tr>';
            }
            var $tr = $(string);
            //把创建出来的$tr追加到tbody中去.
           $('#informationTable').empty().append($tr);
        })

    })
    //每个航班删除按钮
    $('#informationTable').on('click', '.delButton', function () {
       $('#delConfirm').attr('flightid',$(this).attr('flightid'));
    })

   //每个航班修改按钮
    $('#informationTable').on('click', '.alterButton', function () {
        // 为修改按钮添加航班主键值
        $('#ChangButton').attr('flightid',$(this).attr('flightid'));
         // 获取修改航班的id
         fid= $(this).attr('flightid');
         $.get('http://localhost/flights/'+fid, function (res) {
            
            
                $("#changeFlightNumber").val(res.data.flightInformation['flightNum']);
                $("#changeDepartureCity").val(res.data.flightInformation['departure']);
                $("#changeArrivalCity").val(res.data.flightInformation['destination']);
                $("#changeAirlineCompany").val(res.data.flightInformation['airline']);
                $("#chanegDepartureTime").val(res.data.flightInformation['departureTime']);
                $("#changeArrivalTime").val(res.data.flightInformation['arrivalTime']);
                $("#changeBusinessPrice").val(res.data.flightInformation['businessClassPrice']);
                $("#changeEconomyPrice").val(res.data.flightInformation['economyClassPrice']);
            
        })
    })

    // 确定删除按钮
    $("#delConfirm").on("click", function () {
      fid= $(this).attr('flightid');
      $.ajax({
        type: 'delete',//请求方式
        url: 'http://localhost/flights/' + fid,
        success: function (res) {
            if (res.code != 200) return alert('删除信息失败');
            else alert('删除成功！！！');
            // 重新获取航班信息
            get_information();
        }
    })
    $('#modalExitButton').click();//航班添加隐藏
    })

    // 航班确定修改按钮
    $("#ChangButton").on("click", function () {
        // 获取修改航班的id
        fid= $(this).attr('flightid');
        num = $('#changeFlightNumber').val().trim();//航班号
        departureCity = $('#changeDepartureCity').val().trim();//出发城市
        arrivalCity = $('#changeArrivalCity').val().trim();//到达城市
        airlineCompany = $('#changeAirlineCompany').val().trim();//航空公司
        departureTime = $('#chanegDepartureTime').val();//出发时间
        departureTime = departureTime.replace('T', " ");
        departureTime+=":00";
        arrivalTime = $('#changeArrivalTime').val();//到达时间
        arrivalTime = arrivalTime.replace('T', " ");
        arrivalTime +=":00"
        businessPrice = $('#changeBusinessPrice').val();//商务舱价格
        economyPrice = $('#changeEconomyPrice').val();//经济舱价格
        // 发送修改请求
        $.ajax({
            type: 'put',//请求方式
            url: 'http://localhost/flights',
            data:JSON.stringify({ 
                "fid":fid,
                "flightNum": num,
                "departure": departureCity,
                "destination": arrivalCity,
                "airline": airlineCompany,
                "departureTime": departureTime,
                "arrivalTime":arrivalTime,
                "businessClassPrice":businessPrice,
                "economyClassPrice":economyPrice
                }),
                contentType:"application/json",
               // Authorization:'Bearer '+localStorage.getItem("userToken"),
            success: function (res) {
                if (res.code != 200) return alert('修改信息失败');
                else 
                {

                    alert('修改成功！！！');
                // 重新获取航班信息
                get_information();
            }
            }
        })

    })
    
    // 添加按钮
    $("#addButton").on("click", function () {
        num = $('#flightNumber2').val().trim();
        if (num == "") {
            alert("请输入航班号")
            return;
        }
        departureCity = $('#addDepartureCity').val().trim();//出发城市
        if (departureCity == "") {
            alert("请输入出发地")
            return;
        }
        arrivalCity = $('#addArrivalCity').val().trim();//到达城市
        if (arrivalCity == "") {
            alert("请输入到达地")
            return;
        }
        airlineCompany = $('#airlineCompany').val().trim();//到达城市
        if (airlineCompany == "") {
            alert("请输入航空公司")
            return;
        }
        var now = new Date();//现在时间
        departureTime = $('#departureTime').val();//起飞时间
        departureTime = departureTime.replace('T', " ");
        departureTime+=":00";
        var date1 = new Date(departureTime).getTime();//起飞时间时间戳

        if (date1 < now) {
            alert("当前时间已过起飞时间")
            return;
        }
      
        arrivalTime = $('#arrivalTime').val();//到达时间
        arrivalTime = arrivalTime.replace('T', " ");
        arrivalTime +=":00";
        var date2 = new Date(arrivalTime).getTime();//时间戳
        if (date2 <= date1) {
            alert("降落时间早于起飞时间")
            return;
        }

        businessNum = $('#businessNum').val().trim();//公务舱数量
        if (businessNum == "") {
            alert("请输入公务舱数量")
            return;
        }
        businessPrice = $('#businessPrice').val().trim();//公务舱数量
        if (businessPrice == "") {
            alert("请输入公务舱票价")
            return;
        }
        economyNum = $('#economyNum').val().trim();//公务舱数量
        if (economyNum == "") {
            alert("请输入经济舱人数")
            return;
        }
        economyPrice = $('#economyPrice').val().trim();//公务舱数量
        if (economyPrice == "") {
            alert("请输入经济舱票价")
            return;
        }
        $.ajax({
            type:'post',//请求方式
            url:'http://localhost/flights',
            data:JSON.stringify({ 
                "departure": departureCity,
                "destination": arrivalCity,
                "departureTime": departureTime,
                "arrivalTime": arrivalTime,
                "economyClassPrice": economyPrice,
                "economyClassSeats": economyNum,
                "businessClassPrice":  businessPrice,
                "businessClassSeats": businessNum,
                "airline": airlineCompany,
                "flightNum": num
            }),
            contentType:"application/json",
            success:function(res){
                console.log(res);
                if(res.code!=200)return alert(res.message);
                else{
                    alert(res.message);
                    // 重新获取航班信息
                    get_information();
                }
            }
        })
    })

});